<?php
error_reporting('IGNORE_REPEATED_ERRORS');



$document = $_POST["document"];


if (strlen($document)<1) {
	echo "<html>";
	echo "<HEAD>";
	echo "</HEAD>";
	echo "<body>";
	echo "<form name=\"report_form\" id=\"report_form\" action=\"upload.php\" method=\"post\">";
	echo "Cut and Paste Document to process here:<BR>";
	echo "<textarea name=\"document\" id=\"document\" rows=20 cols=80 value=\"\"></textarea><BR>";
	echo "Open document, select all, copy.  Then paste into the above form.<BR>";
	echo "<input type=\"submit\" value=\"Process\"/> <BR>";
	echo "<br>";
	echo "</body>";
	echo "</html>";
}else{
	header('Content-type: application/excel');
	header('Content-Disposition: attachment; filename="parsed_document.csv"');
	readfile('parsed_document.csv');

	echo "MEMBER, NAME, AGE, SEX, COUNTY, HCID, PHONE, CURRENT GRP ID,";
	echo " CURRENT GRP DESC, CURRENT RATE, RENEWAL RATE\r\n";
	$matches = split("\t", $document);
	$last = "";
	foreach($matches as $item){
		$item = trim($item);

			switch ($last){
				case 'MEMBER:':
					echo $item.",";
					break;
				case 'NAME:':
					echo "\"".$item."\",";
					break;
				case 'AGE:':
					echo $item.",";
					break;
				case 'SEX:':
					echo $item.",";
					break;
				case 'COUNTY:':
					echo $item.",";
					break;
				case 'HCID:':
					echo $item.",";
					break;
				case 'PHONE:':
					echo $item.",";
					break;
				case 'CURRENT GRP:':
					if( preg_match("/,/",$item) ){
						echo "\"".$item."\",";
					}else{
						echo $item.",";
					}
					break;
				case 'Rate:':
					echo $item.",";
					break;
				case 'OPTION 1:':
					$renewal_count = 1;
					break;
			}

			if($renewal_count==3){
				echo $item."\r\n";
				$renewal_count=0;
			}elseif($renewal_count>0){
				$renewal_count = $renewal_count + 1;
			}

		$last = $item;
	}
	
}

?>
